package com.ev.apis.controller.scm;

import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.entity.vo.MapExcelConstants;
import cn.afterturn.easypoi.entity.vo.TemplateExcelConstants;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ev.apis.model.DsResultResponse;
import com.ev.asl.constant.AslConstant;
import com.ev.asl.dao.CheckResultDao;
import com.ev.asl.dao.CheckResultDetailDao;
import com.ev.asl.domain.AslComplaintsDO;
import com.ev.asl.domain.CheckResultDetailDO;
import com.ev.asl.service.AslComplaintService;
import com.ev.asl.service.CheckStatisticsService;
import com.ev.asl.vo.AslComplaintsVO;
import com.ev.asl.vo.CheckResultDetail2VO;
import com.ev.custom.vo.StockInItemVO;
import com.ev.custom.vo.StockInVO;
import com.ev.framework.annotation.EvApiByToken;
import com.ev.framework.config.Constant;
import com.ev.framework.config.ConstantForGYL;
import com.ev.framework.utils.*;
import com.ev.mes.domain.ProductionPlanDO;
import com.ev.mes.service.ProductionPlanService;
import com.ev.scm.dao.AslBarStockDao;
import com.ev.scm.domain.AslBarStockDO;
import com.ev.scm.domain.PurchaseDO;
import com.ev.scm.domain.StockInDO;
import com.ev.scm.service.StockInItemService;
import com.ev.scm.service.StockInService;
import com.google.common.collect.Maps;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.ss.usermodel.Workbook;
import org.jodconverter.DocumentConverter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author Kuzi
 * @Date 2020-1-17 16:57
 *
 **/
@Api(value="/",tags = "生产入库")
@RestController
public class ScmProduceInStockApiController {
    @Autowired
    private StockInService stockInService;
    @Autowired
    private AslBarStockDao aslBarStockDao;
    @Autowired
    private CheckResultDao dao;
    @Autowired
    private CheckStatisticsService checkStatisticsService;
    @Autowired
    private AslComplaintService aslComplaintService;


    @Value("${jodconverter.local.office-home}")
    private String pdfPath;
    @Resource
    private DocumentConverter documentConverter; // 具 体 转 换 方 法 参 数 是 java.io.File

    //基本路
    @Value("${org.ftp.basePath}")
    private String basePath;
    //本地路径
    @Value("${org.ftp.localPath}")
    private String localPath;

    @Autowired
    private CheckResultDetailDao detailDao;

    @Autowired
    private StockInItemService stockInItemService;
    @Autowired
    private ProductionPlanService planService;


    @EvApiByToken(value = "/apis/scm/produceInStock/saveAndChange", method = RequestMethod.POST, apiTitle = "新增/修改—生产入库")
    @ApiOperation("新增/修改—生产入库")
    @Transactional(rollbackFor = Exception.class)
    public R addAndEdit(StockInDO stockInDO,
                        @ApiParam(value = "产品/物料明细行[\n" +
                                "{\"materielId\":2,\n" +
                                "\"id\":\"明细主键（修改时必传）\",\n" +
                                "\"batch\":\"批次\",\n" +
                                "\"count\":数量,\n" +
                                "\"unitPrice\":单价,\n" +
                                "\"amount\":金额,\n" +
                                "\"warehouse\":仓库,\n" +
                                "\"warehLocation\":库位,\n" +
                                "\"sourceType\":源单类型,\n" +
                                "\"sourceCode\":\"原单编码\"\n" +
                                "\"sourceId\":\"原单id(追溯用，必传)\"\n" +
                                "\"qrcodeId\":\"二维码主键id\"\n" +
                                "}\n" +
                                "]", required = true) @RequestParam(value = "bodyDetail", defaultValue = "") String bodyDetail,
                        @ApiParam(value = "删除的明细id") @RequestParam(value = "itemIds", required = false) Long[] itemIds) {

        R result = stockInService.checkSourceCountsOfProduce(bodyDetail,stockInDO.getId());
        if(Objects.isNull(result)){
            return stockInService.addAndChangeInStockType(stockInDO,ConstantForGYL.YDGOODS_WAREHOUSE,bodyDetail,itemIds);
        }else{
            return result;
        }
    }
    //    @EvApiByToken(value = "/apis/scm/produceInStock/saveAndChangeByTray", method = RequestMethod.POST, apiTitle = "新增/修改—扫码入库")
//    @ApiOperation("新增/修改—扫码入库")
//    public R addAndEditByTray(@Valid AslBarStockDO aslBarStockDO) {
//
//        return stockInService.barInStock(aslBarStockDO);
//    }
    @EvApiByToken(value = "/apis/scm/produceInStock/saveAndChangeByTray", method = RequestMethod.POST, apiTitle = "新增/修改—扫码入库")
    @ApiOperation("新增/修改—扫码入库")
    public R addAndEditByTray(@RequestBody StockInVO stockInVO) {

        return stockInService.barInStock(stockInVO);
    }

    @EvApiByToken(value = "/apis/scm/produceInStock/auditStatusChange", method = RequestMethod.POST, apiTitle = "审核--生产入库")
    @ApiOperation("审核--生产入库")
    @Transactional(rollbackFor = Exception.class)
    public R changeAuditStatus(@ApiParam(value = "生产入库主表主键", required = true) @RequestParam(value = "inHeadId") Long inHeadId,
                               @ApiParam(value = "审核人主键") @RequestParam(value = "auditor",required = false) Long auditor) {
        auditor= ShiroUtils.getUserId();
        return stockInService.auditAllTypeInStock(inHeadId, auditor, ConstantForGYL.YDGOODS_WAREHOUSE);
    }

    @EvApiByToken(value = "/apis/scm/produceInStock/reverseAuditChange", method = RequestMethod.POST, apiTitle = "反审核--生产入库")
    @ApiOperation("反审核--生产入库")
    @Transactional(rollbackFor = Exception.class)
    public R reverseAudit(@ApiParam(value = "生产入库主表主键", required = true) @RequestParam(value = "inHeadId") Long inHeadId) {

        return stockInService.disAuditInStock(inHeadId, ConstantForGYL.YDGOODS_WAREHOUSE);
    }

    @EvApiByToken(value = "/apis/scm/produceInStock/deletAllStock", method = RequestMethod.POST, apiTitle = "删除--生产入库")
    @ApiOperation("删除--生产入库")
    @Transactional(rollbackFor = Exception.class)
    public R remoceOtherWaitAuite(@ApiParam(value = "生产入库主表主键", required = true) @RequestParam(value = "inHeadIds") Long[] inHeadIds) {

        return  stockInService.deleteBatch(inHeadIds);
    }

    @EvApiByToken(value = "/apis/scm/produceInStock/list", method = RequestMethod.POST, apiTitle = "生产入库列表/查询/高级查询")
    @ApiOperation("生产入库列表/查询/高级查询")
    public R otherHeadDetailList(@ApiParam(value = "当前第几页") @RequestParam(value = "pageno", defaultValue = "1", required = false) int pageno,
                                 @ApiParam(value = "一页多少条") @RequestParam(value = "pagesize", defaultValue = "20", required = false) int pagesize,
                                 @ApiParam(value = "单据编号") @RequestParam(value = "inheadCode", defaultValue = "", required = false) String inheadCode,
                                 @ApiParam(value = "物料名（模糊）") @RequestParam(value = "materielName", defaultValue = "", required = false) String materielName,
                                 @ApiParam(value = "入库起始时间") @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
                                 @ApiParam(value = "入库截止时间") @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
                                 @ApiParam(value = "生产部门名字") @RequestParam(value = "deptName", defaultValue = "", required = false) String deptName,
                                 @ApiParam(value = "生产部门id") @RequestParam(value = "deptId", defaultValue = "", required = false) Long deptId,
                                 @ApiParam(value = "规格型号") @RequestParam(value = "specification", defaultValue = "", required = false) String specification,
                                 @ApiParam(value = "批次") @RequestParam(value = "batch", defaultValue = "", required = false) String batch,
                                 @ApiParam(value = "审核状态") @RequestParam(value = "auditSign", defaultValue = "", required = false) Long auditSign,
                                 @ApiParam(value = "入库操作员id") @RequestParam(value = "operator", defaultValue = "", required = false) Long operator,
                                 @ApiParam(value = "入库操作员名字") @RequestParam(value = "operatorName", defaultValue = "", required = false) String operatorName,
                                 @ApiParam(value = "核算时间") @RequestParam(value = "periodTime", defaultValue = "", required = false) String periodTime,
                                 @ApiParam(value = "制单人id") @RequestParam(value = "createBy", defaultValue = "", required = false) Long createBy,
                                 @ApiParam(value = "制单人名字") @RequestParam(value = "createByName", defaultValue = "", required = false) String createByName,
                                 @ApiParam(value = "制单时间") @RequestParam(value = "createTime", defaultValue = "", required = false) String  createTime  ) {
        Map<String, Object> resulst = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        params.put("offset", (pageno - 1) * pagesize);
        params.put("limit", pagesize);
        params.put("inheadCode", inheadCode);
        params.put("materielName",materielName );
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("deptName",deptName );
        params.put("deptId",deptId);
        params.put("materielSpecification",specification );
        params.put("batch", batch);
        params.put("auditSign",auditSign);
        params.put("operator", operator);
        params.put("operatorName",operatorName);
        params.put("createBy",createBy );
        params.put("createByName", createByName);
        params.put("createTime", createTime);
        params.put("storageType", ConstantForGYL.YDGOODS_WAREHOUSE);
        if(StringUtils.isNotEmpty(periodTime)){
            Date periodTimes = DateFormatUtil.getDateByParttern(periodTime, "yyyy-MM-dd");
            params.put("startPeriodTime", DatesUtil.getSupportBeginDayOfMonth(periodTimes));
            params.put("endPeriodTime", DatesUtil.getSupportEndDayOfMonth(periodTimes));
        }

        Map<String, Object> totalForMap = stockInService.countForMap(params);
        List<Map<String, Object>> detailList = stockInService.listForMap(params);

        if (!detailList.isEmpty()) {
            List<String> sourceCodes = detailList.stream().filter(e -> e.containsKey("sourceCode")).map(e -> e.get("sourceCode").toString()).collect(Collectors.toList());
            if (sourceCodes.size() > 0) {
                Map<String,Object> param = Maps.newHashMap();
                param.put("codes",sourceCodes);
                List<ProductionPlanDO> list = planService.list(param);
                Map<String, Long> codeToId = list.stream().collect(Collectors.toMap(ProductionPlanDO::getPlanNo, ProductionPlanDO::getId));
                detailList.forEach(e->{
                    String sourceCode = e.getOrDefault("sourceCode", "").toString();
                    e.put("queryId",codeToId.get(sourceCode));
                });
            }

            Map<String, Object> dsRet = new HashMap<>();
            dsRet.put("pageno",pageno);
            dsRet.put("pagesize",pagesize);
            dsRet.put("totalPages",(Integer.parseInt(totalForMap.get("count").toString()) + pagesize - 1) / pagesize);
            dsRet.put("totalRows",totalForMap.get("count"));
            dsRet.put("toatalCount",totalForMap.get("toatalCount"));
            dsRet.put("toatalAmount",totalForMap.get("toatalAmount"));
            dsRet.put("datas",detailList);
            resulst.put("data", dsRet);
        }
        return R.ok(resulst);
    }
    @EvApiByToken(value = "/apis/scm/produceInStock/list2", method = RequestMethod.POST, apiTitle = "生产入库列表/查询/高级查询")
    @ApiOperation("生产入库列表/查询/高级查询")
    public R otherHeadDetailList2(@ApiParam(value = "当前第几页") @RequestParam(value = "pageno", defaultValue = "1", required = false) int pageno,
                                  @ApiParam(value = "一页多少条") @RequestParam(value = "pagesize", defaultValue = "20", required = false) int pagesize,
                                  @ApiParam(value = "单据编号") @RequestParam(value = "inheadCode", defaultValue = "", required = false) String inheadCode,
                                  @ApiParam(value = "物料名（模糊）") @RequestParam(value = "materielName", defaultValue = "", required = false) String materielName,
                                  @ApiParam(value = "入库起始时间") @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
                                  @ApiParam(value = "入库截止时间") @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
                                  @ApiParam(value = "生产部门名字") @RequestParam(value = "deptName", defaultValue = "", required = false) String deptName,
                                  @ApiParam(value = "生产部门id") @RequestParam(value = "deptId", defaultValue = "", required = false) Long deptId,
                                  @ApiParam(value = "规格型号") @RequestParam(value = "specification", defaultValue = "", required = false) String specification,
                                  @ApiParam(value = "批次") @RequestParam(value = "batch", defaultValue = "", required = false) String batch,
                                  @ApiParam(value = "审核状态") @RequestParam(value = "auditSign", defaultValue = "", required = false) Long auditSign,
                                  @ApiParam(value = "入库操作员id") @RequestParam(value = "operator", defaultValue = "", required = false) Long operator,
                                  @ApiParam(value = "入库操作员名字") @RequestParam(value = "operatorName", defaultValue = "", required = false) String operatorName,
                                  @ApiParam(value = "核算时间") @RequestParam(value = "periodTime", defaultValue = "", required = false) String periodTime,
                                  @ApiParam(value = "出入库表id") @RequestParam(value = "id", defaultValue = "", required = false) Long id,
                                  @ApiParam(value = "制单人id") @RequestParam(value = "createBy", defaultValue = "", required = false) Long createBy,
                                  @ApiParam(value = "制单人名字") @RequestParam(value = "createByName", defaultValue = "", required = false) String createByName,
                                  @ApiParam(value = "制单时间") @RequestParam(value = "createTime", defaultValue = "", required = false) String  createTime  ) {
        Map<String, Object> resulst = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        params.put("offset", (pageno - 1) * pagesize);
        params.put("limit", pagesize);
        params.put("inheadCode", inheadCode);
        params.put("materielName",materielName );
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("status", 0);
        params.put("deptName",deptName );
        params.put("deptId",deptId);
        params.put("materielSpecification",specification );
        params.put("batch", batch);
        params.put("auditSign",auditSign);
        params.put("operator", operator);
        params.put("operatorName",operatorName);
        params.put("createBy",createBy );
        params.put("id",id );
        params.put("createByName", createByName);
        params.put("createTime", createTime);
        params.put("storageType", ConstantForGYL.YDGOODS_WAREHOUSE);
        if(StringUtils.isNotEmpty(periodTime)){
            Date periodTimes = DateFormatUtil.getDateByParttern(periodTime, "yyyy-MM-dd");
            params.put("startPeriodTime", DatesUtil.getSupportBeginDayOfMonth(periodTimes));
            params.put("endPeriodTime", DatesUtil.getSupportEndDayOfMonth(periodTimes));
        }

//        Map<String, Object> totalForMap = stockInService.countForMap(params);

//        List<Map<String, Object>> detailList = stockInService.listForMap(params);
        List<Map<String, Object>> detailList2 = aslBarStockDao.listInStock2(params);
        Map<String, Object> totalForMap = aslBarStockDao.countInTotal(params);
        if (!detailList2.isEmpty()) {
//        if (!detailList.isEmpty()) {
//            List<String> sourceCodes = detailList.stream().filter(e -> e.containsKey("sourceCode")).map(e -> e.get("sourceCode").toString()).collect(Collectors.toList());
//            if (sourceCodes.size() > 0) {
//                Map<String,Object> param = Maps.newHashMap();
//                param.put("codes",sourceCodes);
//                List<ProductionPlanDO> list = planService.list(param);
//                Map<String, Long> codeToId = list.stream().collect(Collectors.toMap(ProductionPlanDO::getPlanNo, ProductionPlanDO::getId));
//                detailList.forEach(e->{
//                    String sourceCode = e.getOrDefault("sourceCode", "").toString();
//                    e.put("queryId",codeToId.get(sourceCode));
//                });
//            }

            Map<String, Object> dsRet = new HashMap<>();
            dsRet.put("pageno",pageno);
            dsRet.put("pagesize",pagesize);
            dsRet.put("totalPages",(Integer.parseInt(totalForMap.get("total").toString()) + pagesize - 1) / pagesize);
            dsRet.put("totalRows",totalForMap.get("total"));
//            dsRet.put("toatalCount",totalForMap.get("toatalCount"));
//            dsRet.put("toatalAmount",totalForMap.get("toatalAmount"));
            dsRet.put("datas",detailList2);
            resulst.put("data", dsRet);
        }
        return R.ok(resulst);
    }


    @EvApiByToken(value = "/apis/scm/produceInStock/getDtailOfOtherIn", method = RequestMethod.POST, apiTitle = "详情--生产入库")
    @ApiOperation("获取详情--生产入库")
    public R getDetail(@ApiParam(value = "生产入库主表主键", required = true) @RequestParam(value = "inHeadIds", defaultValue = "") Long inHeadIds) {

        Map<String, Object> params = Maps.newHashMapWithExpectedSize(1);
        params.put("id",inHeadIds);
//        Map<String, Object> deatilOfhead = stockInService.deatilOfhead(params);
//        List<Map<String, Object>> deatilOfBody = stockInItemService.deatilOfBody(params);

        List<Map<String, Object>> detailList = aslBarStockDao.listInStock(params);
//        Map<String, Object> production = aslBarStockDao.getProductionById(params);
        if (ObjectUtils.isEmpty(detailList) || detailList.size()<=0)        return R.ok();

        Map<String, Object> detail = detailList.get(0);
        params.clear();
        Map<String,Object>  map= new HashMap<>();
        List<Map<String, Object>> deatilOfBody = new ArrayList<>();
        Map<String, Object> deatilOfhead = new HashMap<>();
        deatilOfhead.put("inOutTime",detail.get("inOutTime"));
        deatilOfhead.put("specification",detail.get("specification"));
        deatilOfhead.put("crateByName",detail.get("crateByName"));
        deatilOfhead.put("createBy",detail.get("createBy"));
        deatilOfhead.put("createTime",detail.get("inOutTime"));
        deatilOfhead.put("unitName",detail.get("unitName"));
        deatilOfhead.put("unitPrice",detail.get("unitName"));
        deatilOfhead.put("batch",detail.get("batch_no"));
        deatilOfhead.put("deptName",detailList.get(0).get("deptName"));
        deatilOfhead.put("deptId",detailList.get(0).get("deptId"));
        deatilOfhead.put("warehouseName",detail.get("warehouseName"));
        deatilOfhead.put("warehLocationName",detail.get("warehLocationName"));

        detailList.forEach(data ->{
            Map<String, Object> body = new HashMap<>();
            body.put("serialno",data.get("serialno"));
            body.put("proName",data.get("materielName"));
            body.put("specification",data.get("specification"));
            body.put("unitName",data.get("unitName"));
            body.put("count",data.get("sum"));
            body.put("warehouseName",data.get("warehouseName"));
            body.put("unitPrice",data.get("salePrice"));
            body.put("warehouse",data.get("warehouseName"));
            body.put("warehLocation",data.get("warehouseName"));
            body.put("batch",data.get("batch_no"));
            body.put("warehLocationName",data.get("warehLocationName"));
            body.put("sourceTypeName",data.get("sourceTypeName"));
            deatilOfBody.add(body);
        });
//        body.put("deptName",production.get("deptName"));
//        body.put("deptId",production.get("deptId"));
//        body.put("sourceCode",production.get("plan_no"));
//        body.put("sourceId",production.get("id"));
//        body.put("pro_dept",production.get("pro_dept"));
        if(Objects.nonNull(deatilOfhead)){
            map.put("deatilOfhead",deatilOfhead);
            map.put("deatilOfBody",deatilOfBody);
            params.put("data",map);
        }
        return R.ok(params);
    }




    @ResponseBody
    @EvApiByToken(value = "/apis/exportExcel/produceInStocketOut2", method = RequestMethod.GET, apiTitle = "导出生产入库")
    @ApiOperation("导出生产入库")
    public void exportExcel(
            @ApiParam(value = "单据编号") @RequestParam(value = "inheadCode", defaultValue = "", required = false) String inheadCode,
            @ApiParam(value = "物料名（模糊）") @RequestParam(value = "materielName", defaultValue = "", required = false) String materielName,
            @ApiParam(value = "入库起始时间") @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
            @ApiParam(value = "入库截止时间") @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
            @ApiParam(value = "生产部门名字") @RequestParam(value = "deptName", defaultValue = "", required = false) String deptName,
            @ApiParam(value = "规格型号") @RequestParam(value = "specification", defaultValue = "", required = false) String specification,
            @ApiParam(value = "批次") @RequestParam(value = "batch", defaultValue = "", required = false) String batch,
            @ApiParam(value = "审核状态") @RequestParam(value = "auditSign", defaultValue = "", required = false) Long auditSign,
            @ApiParam(value = "入库操作员id") @RequestParam(value = "operator", defaultValue = "", required = false) Long operator,
            @ApiParam(value = "入库操作员名字") @RequestParam(value = "operatorName", defaultValue = "", required = false) String operatorName,
            @ApiParam(value = "制单人id") @RequestParam(value = "createBy", defaultValue = "", required = false) Long createBy,
            @ApiParam(value = "制单人名字") @RequestParam(value = "createByName", defaultValue = "", required = false) String createByName,
            @ApiParam(value = "制单时间") @RequestParam(value = "createTime", defaultValue = "", required = false) String  createTime,
            HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {

        Map<String, Object> params = new HashMap<>();
        params.put("inheadCode", inheadCode);
        params.put("materielName",materielName );
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("deptName",deptName );
        params.put("materielSpecification",specification );
        params.put("batch", batch);
        params.put("auditSign",auditSign);
        params.put("operator", operator);
        params.put("operatorName",operatorName);
        params.put("createBy",createBy );
        params.put("createByName", createByName);
        params.put("createTime", createTime);
        params.put("storageType", ConstantForGYL.YDGOODS_WAREHOUSE);

        List<Map<String, Object>> list = stockInService.listForMap(params);

        ClassPathResource classPathResource = new ClassPathResource("poi/scm_produce_in_stock.xlsx");
        Map<String,Object> map = Maps.newHashMap();
        JSONArray format = JSONUtils.format(list);
        map.put("list", format);
        TemplateExportParams result = new TemplateExportParams(classPathResource.getPath());
        modelMap.put(TemplateExcelConstants.FILE_NAME, "生产入库");
        modelMap.put(TemplateExcelConstants.PARAMS, result);
        modelMap.put(TemplateExcelConstants.MAP_DATA, map);
        PoiBaseView.render(modelMap, request, response,
                TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);
    }
    @ResponseBody
    @EvApiByToken(value = "/apis/exportExcel/checkOut", method = RequestMethod.GET, apiTitle = "导出检查成绩单")
    @ApiOperation("导出检查成绩单")
    public void exportExcel2(
            @ApiParam(value = "检查成绩单id") @RequestParam(value = "id", defaultValue = "", required = false) Long  id,
            HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {


        Map<String,Object> map = Maps.newHashMap();
        Map<String, Object> result = dao.getDetailInfo(id);
        if (Objects.nonNull(result)) {
            result.put("billDate", ObjectUtils.isEmpty(result.get("billDate")) ? null : DateUtils.format((Date) result.get("billDate"),DateUtils.DATE_PATTERN));
            List<CheckResultDetailDO> detailDOS = detailDao.list(Long.valueOf(String.valueOf(result.get("id"))));
            caculate(detailDOS,map,1);
            map.put("qualityInspectorName", result.get("qualityInspectorName"));//品质检查者id
            map.put("qualityBearerName", result.get("qualityBearerName"));//品质担当者ID
            map.put("instructionQty", ObjectUtils.isEmpty(result.get("instructionQty")) ? "0" : (int)Double.parseDouble(result.get("instructionQty").toString().trim()));//
            map.put("billDate", result.get("billDate"));//
            map.put("batchNo", result.get("batchNo"));//
            map.put("remarks", result.get("remarks"));//
//            map.put("material", result.get("materialName")+"-"+result.get("specification"));//
            map.put("material",ObjectUtils.isEmpty(result.get("specification")) ? result.get("materialName") : (result.get("materialName")+"-"+result.get("specification")));
        }

        ClassPathResource classPathResource = new ClassPathResource("poi/inspection_result_2.xlsx");
        TemplateExportParams template = new TemplateExportParams(classPathResource.getPath());
        modelMap.put(TemplateExcelConstants.FILE_NAME, "检查成绩书");
        modelMap.put(TemplateExcelConstants.PARAMS, template);
        modelMap.put(TemplateExcelConstants.MAP_DATA, map);
        PoiBaseView.render(modelMap, request, response,
                TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);
    }

    @ResponseBody
    @EvApiByToken(value = "/apis/exportExcel/rawMaterialInspectionCheckout", method = RequestMethod.GET, apiTitle = "导出原料检验成绩单")
    @ApiOperation("导出原料检验成绩单")
    public void rawMaterialInspectionCheckout(
            @ApiParam(value = "检查成绩单id") @RequestParam(value = "id", defaultValue = "", required = false) Long  id,
            HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {

        Map<String,Object> map = Maps.newHashMap();
        Map<String, Object> result = dao.getDetailInfo(id);
        if (Objects.nonNull(result)) {
            result.put("billDate", ObjectUtils.isEmpty(result.get("billDate")) ? null : DateUtils.format((Date) result.get("billDate"),DateUtils.DATE_PATTERN));
            List<CheckResultDetailDO> detailDOS = detailDao.list(Long.valueOf(String.valueOf(result.get("id"))));
            handleData(detailDOS,map,1);
            map.put("qualityInspectorName", result.get("qualityInspectorName"));//品质检查者id
            map.put("qualityBearerName", result.get("qualityBearerName"));//品质担当者ID
            map.put("instructionQty", ObjectUtils.isEmpty(result.get("qty")) ? "0" : (int)Double.parseDouble(result.get("qty").toString().trim()));//
            map.put("billDate", result.get("billDate"));//
            map.put("batchNo", result.get("batchNo"));//
            map.put("remarks", result.get("remarks"));//
//            map.put("material", result.get("materialName")+"-"+result.get("specification"));//
            map.put("material",ObjectUtils.isEmpty(result.get("specification")) ? result.get("materialName") : (result.get("materialName")+"-"+result.get("specification")));
        }

        ClassPathResource classPathResource = new ClassPathResource("poi/raw_material_inspection.xlsx");
        TemplateExportParams template = new TemplateExportParams(classPathResource.getPath());
        modelMap.put(TemplateExcelConstants.FILE_NAME, "原料检验成绩书");
        modelMap.put(TemplateExcelConstants.PARAMS, template);
        modelMap.put(TemplateExcelConstants.MAP_DATA, map);
        PoiBaseView.render(modelMap, request, response,
                TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);
    }

    @ResponseBody
    @EvApiByToken(value = "/apis/exportExcel/checkOut4", method = RequestMethod.GET, apiTitle = "导出检查成绩单")
    @ApiOperation("导出检查成绩单")
    public void exportExcel2222(
            @ApiParam(value = "检查成绩单id") @RequestParam(value = "id", defaultValue = "", required = false) Long  id,
            @ApiParam(value = "批号") @RequestParam(value = "batch1", defaultValue = "", required = false) String  batch1,
            @ApiParam(value = "批号") @RequestParam(value = "batch2", defaultValue = "", required = false) String  batch2,
            @ApiParam(value = "批号") @RequestParam(value = "specification", defaultValue = "", required = false) String  specification,
            HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {

        String batch = "";
        Integer num = 0;

        if (ObjectUtil.isEmpty(batch1) && ObjectUtil.isEmpty(batch2)){
            return ;
        }
        if (ObjectUtil.isEmpty(batch2)){
            batch = batch1;
            num = 1;
        }else if (ObjectUtil.isEmpty(batch1)){
            batch = batch2;
            num = 1;
        }else {

            Integer num1 = new Integer(batch1.substring(batch1.length()-3));
            Integer num2 = new Integer(batch2.substring(batch2.length()-3));
            num = (num1 > num2) ? (num1 - num2 + 1) : (num2 - num1 + 1);
            batch = (num1 > num2) ? (batch2 + "-" + batch1.substring(batch1.length() - 3)) : (batch1 + "-" + batch2.substring(batch1.length() - 3));
        }
        Map<String,Object> map = Maps.newHashMap();
        Map<String, Object> result = dao.getDetailInfo(id);
        if (Objects.nonNull(result)) {
            result.put("billDate", ObjectUtils.isEmpty(result.get("billDate")) ? null : DateUtils.format((Date) result.get("billDate"),DateUtils.DATE_PATTERN));
            List<CheckResultDetailDO> detailDOS = detailDao.list(Long.valueOf(String.valueOf(result.get("id"))));
            caculate(detailDOS,map,2);
            map.put("qualityInspectorName", result.get("qualityInspectorName"));//品质检查者id
            map.put("qualityBearerName", result.get("qualityBearerName"));//品质担当者ID
            map.put("instructionQty", ObjectUtils.isEmpty(result.get("instructionQty")) ? "0" : (int)Double.parseDouble(result.get("instructionQty").toString().trim()));//
            map.put("billDate", result.get("billDate"));//
            map.put("batchNo", result.get("batchNo"));//
            map.put("remarks", result.get("remarks"));//
            map.put("material",ObjectUtils.isEmpty(specification) ?
                    result.get("materialName") : (result.get("materialName")+"-"+specification));
        }
        map.put("batchNo",batch);
        map.put("instructionQty",num);

//        ClassPathResource classPathResource = new ClassPathResource("poi/inspection_result_10.xlsx");
//        TemplateExportParams templatePath = new TemplateExportParams(classPathResource.getPath());

        //生成excel
        String templateFileName = localPath + File.separator + basePath + File.separator + "templates" + File.separator + "result6.xlsx";
//        TemplateExportParams templatePath = new TemplateExportParams(templateFileName);
        TemplateExportParams templatePath = new TemplateExportParams(templateFileName);
//        TemplateExportParams templatePath = new TemplateExportParams("D:\\DownLoad\\Google\\result6.xlsx");
        Workbook workbook = ExcelExportUtil.exportExcel(templatePath, map);
        String fileName = DateUtil.format(new Date(), "yyyy-MM-dd") + System.currentTimeMillis();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(pdfPath + File.separator + "tempFiles"+ File.separator + fileName + ".xlsx");
            workbook.write(fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //excel转化pdf
        try {
            File excelFile = new File(pdfPath + File.separator + "tempFiles"+ File.separator + fileName + ".xlsx");
            File pdfFile = new File(pdfPath + File.separator + "tempFiles"+ File.separator + fileName + ".pdf");
            documentConverter.convert(excelFile).to(pdfFile).execute();
            String fileNameURL = URLEncoder.encode("检查成绩书", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+fileNameURL+";"+"filename*=utf-8''"+fileNameURL);
            File file = new File(pdfPath + File.separator + "tempFiles"+ File.separator + fileName + ".pdf");
            if (!file.exists()) {
                response.sendError(404, "File not found!");
                return;
            }
            String name = URLEncoder.encode("检查成绩书.pdf", "UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + name);
            response.setContentType("application/pdf");
            BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(file.toPath()));
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @ResponseBody
    @EvApiByToken(value = "/apis/exportExcel/checkSumOut", method = RequestMethod.GET, apiTitle = "导出检查成绩单")
    @ApiOperation("导出检查成绩统计单")
    public void checkSumOut(
            @ApiParam(value = "") @RequestParam(value = "pageno", defaultValue = "", required = false) int  pageno,
            @ApiParam(value = "") @RequestParam(value = "pagesize", defaultValue = "", required = false) int  pagesize,
            @ApiParam(value = "产品") @RequestParam(value = "product", defaultValue = "", required = false) Long  product,
            @ApiParam(value = "检验日期") @RequestParam(value = "billDateStart", defaultValue = "", required = false) Date  billDateStart,
            @ApiParam(value = "检验日期") @RequestParam(value = "billDateEnd", defaultValue = "", required = false) Date  billDateEnd,
            HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {

        Map<String, Object> param = Maps.newHashMapWithExpectedSize(5);
        param.put("offset", (pageno - AslConstant.ONE) * pagesize);
        param.put("limit", pagesize);
        param.put("product", product);
        param.put("billDateStart", billDateStart);
        param.put("billDateEnd", billDateEnd);
        param.put("over", 1);
        Map<String,Object> data = checkStatisticsService.query3(param);

        ClassPathResource classPathResource = new ClassPathResource("poi/check_sum.xlsx");
        TemplateExportParams template = new TemplateExportParams(classPathResource.getPath());
        modelMap.put(TemplateExcelConstants.FILE_NAME, "最终检查测定");
        modelMap.put(TemplateExcelConstants.PARAMS, template);
        modelMap.put(TemplateExcelConstants.MAP_DATA, data);
        String encode = "";
        try {
            encode = URLEncoder.encode("最终检查测定"+ ".xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + encode);
        PoiBaseView.render(modelMap, request, response,
                TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);


    }
    @ResponseBody
    @EvApiByToken(value = "/apis/exportExcel/complaint", method = RequestMethod.GET, apiTitle = "导出检查成绩单")
    @ApiOperation("导出客诉信息")
    public void complaintOut(@ApiParam(value = "当前第几页", required = true) @RequestParam(value = "pageno") Integer pageno,
                             @ApiParam(value = "一页多少条", required = true) @RequestParam(value = "pagesize") Integer pagesize,
                             @ApiParam(value = "产品名称", required = true) @RequestParam(value = "productName",required = false) String productName,
                             @ApiParam(value = "QA接收日期", required = true) @RequestParam(value = "startDate",required = false) Date startDate,
                             @ApiParam(value = "QA接收日期", required = true) @RequestParam(value = "endDate",required = false) Date endDate,
                             HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        AslComplaintsDO aslComplaintsDO1 = new AslComplaintsDO();
        if (!ObjectUtils.isEmpty(pageno) && !ObjectUtils.isEmpty(pagesize)){
            aslComplaintsDO1.setOffer((pageno-1)*pagesize);
        }
        aslComplaintsDO1.setLimit(pagesize);
        aslComplaintsDO1.setProductName(productName);
        aslComplaintsDO1.setStartDate(startDate);
        aslComplaintsDO1.setEndDate(endDate);
        List<AslComplaintsDO> complaintsDOS = aslComplaintService.list(aslComplaintsDO1);
        List<AslComplaintsVO> aslComplaintsVOS = new ArrayList<>();
        complaintsDOS.forEach(complaint->{
            AslComplaintsVO vo = new AslComplaintsVO();
            BeanUtils.copyProperties(complaint,vo);
            vo.setReceiveDate(DateUtils.format(complaint.getReceiveDate()));
            vo.setProductioDate(DateUtils.format(complaint.getProductioDate()));
            vo.setReplyTime(DateUtils.format(complaint.getReplyTime(),DateUtils.DATE_TIME_PATTERN));
            aslComplaintsVOS.add(vo);
        });
        Map<String,Object> data = new HashMap<>();
        data.put("complaintsDOS",aslComplaintsVOS);

        ClassPathResource classPathResource = new ClassPathResource("poi/asl_complaints2.xlsx");
//        ClassPathResource classPathResource = new ClassPathResource("poi/instr_sum.xlsx");
        TemplateExportParams template = new TemplateExportParams(classPathResource.getPath());
        modelMap.put(TemplateExcelConstants.FILE_NAME, "客诉信息");
        modelMap.put(TemplateExcelConstants.PARAMS, template);
        modelMap.put(TemplateExcelConstants.MAP_DATA, data);
        String encode = "";
        try {
            encode = URLEncoder.encode("客诉信息"+ ".xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + encode);
        PoiBaseView.render(modelMap, request, response,
                TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);


    }

    public static void main(String[] args) {
        String str = "230708B-01-001-132";
        String substring = str.substring(str.length() - 3);
        System.out.println(substring);
    }
    /**
     *
     * @param detailDOS
     * @param map
     * @param type 1-excel; 2-pdf
     */
    public void caculate(List<CheckResultDetailDO> detailDOS, Map<String,Object> map, Integer type) {
        Boolean waiguan = true;//外观测定结果
        String ok = "合格";
        for (CheckResultDetailDO detailDO : detailDOS) {
            map.put("remark", detailDO.getCheckResult());
            map.put("formula", detailDO.getFormula());
            map.put("specification", detailDO.getSpecification());
            map.put("name", detailDO.getCheckItem());
            map.put("typeName", detailDO.getCheckType() != null ? detailDO.getCheckType() : "");
            map.put("sample", detailDO.getSample());
            map.put("method", detailDO.getCheckWay());
            map.put("targetValue", detailDO.getTargetValue());
            map.put("checkResult", detailDO.getCheckResult());

            String typeName = detailDO.getCheckItem()==null ? "" : detailDO.getCheckItem();
            switch (typeName) {
                case Constant.WAIGUAN://
                    map.put("result1", type.equals(2) ? (ok.equals(detailDO.getCheckResult()) ? "OK" : "NO") : detailDO.getCheckResult());
                    map.put("yangpin1", detailDO.getSample());
//                    map.put("way1", detailDO.getCheckWay());
                    break;
                case Constant.SHUAILUO://
                    map.put("yangpin2", detailDO.getSample());
                    map.put("result2", type.equals(2) ? (ok.equals(detailDO.getCheckResult()) ? "OK" : "NO") : detailDO.getCheckResult());
//                    map.put("way2", detailDO.getCheckWay());
                    break;
                case Constant.LOUSHUI://
                    map.put("yangpin3", detailDO.getSample());
                    map.put("result3", type.equals(2) ? (ok.equals(detailDO.getCheckResult()) ? "OK" : "NO") : detailDO.getCheckResult());
//                    map.put("way3", detailDO.getCheckWay());
                    break;
                case Constant.QIMI://
                    map.put("yangpin4", detailDO.getSample());
                    map.put("result4", type.equals(2) ? (ok.equals(detailDO.getCheckResult()) ? "OK" : "NO") : detailDO.getCheckResult());
//                    map.put("way4", detailDO.getCheckWay());
                    break;
                case Constant.KELIWU://  (((((a > b) ? a : b) > c ) ? ((a > b) ? a : b) : c) * 3.08 / 200 ) <= 10
                    //TODO 颗粒物测定的大小分类 Below 10 EA/ml

                    if(detailDO.getSpecification().equals("Below 10 EA/ml")){
                        map.put("specification1", detailDO.getSpecification());
                        map.put("yangpin5", detailDO.getSample());
                        map.put("result5", type.equals(2) ? (ok.equals(detailDO.getCheckResult()) ? "OK" : "NO") : detailDO.getCheckResult());
                        if (!ObjectUtils.isEmpty(detailDO.getCheckValue())){
                            JSONArray array = JSON.parseArray(detailDO.getCheckValue());
                            if (!ObjectUtils.isEmpty(array)){
                                map.put("val1", org.apache.commons.lang3.StringUtils.join(array,","));
                            }
                        }
                    }
                    if(detailDO.getSpecification().equals("Below 50 EA/ml")){
                        map.put("specification2", detailDO.getSpecification());
                        map.put("yangpin6", detailDO.getSample());
                        map.put("result6", type.equals(2) ? (ok.equals(detailDO.getCheckResult()) ? "OK" : "NO") : detailDO.getCheckResult());
                        if (!ObjectUtils.isEmpty(detailDO.getCheckValue())){
                            JSONArray array = JSON.parseArray(detailDO.getCheckValue());
                            if (!ObjectUtils.isEmpty(array)){
                                map.put("val2", org.apache.commons.lang3.StringUtils.join(array,","));
                            }
                        }
                    }
                    if(detailDO.getSpecification().equals("Below 120 EA/ml")){
                        map.put("specification3", detailDO.getSpecification());
                        map.put("yangpin7", detailDO.getSample());
                        map.put("result7", type.equals(2) ? (ok.equals(detailDO.getCheckResult()) ? "OK" : "NO") : detailDO.getCheckResult());
                        if (!ObjectUtils.isEmpty(detailDO.getCheckValue())){
                            JSONArray array = JSON.parseArray(detailDO.getCheckValue());
                            if (!ObjectUtils.isEmpty(array)){
                                map.put("val3", org.apache.commons.lang3.StringUtils.join(array,","));
                            }
                        }
                    }
                    break;
                case Constant.ZHURUKOUG://a>=58.4 && a<=59.6 && b>=58.4 && b<=59.6 && average>=58.4 && average<=59.6
                    if (!ObjectUtils.isEmpty(detailDO.getCheckValue())){
                        JSONArray array = JSON.parseArray(detailDO.getCheckValue());
                        if (!ObjectUtils.isEmpty(array)){
                            BigDecimal average = array.stream().collect(CustomCollectors.averagingBigDecimal(i -> new BigDecimal(i.toString()), 2, 2));
                            average.setScale(1,BigDecimal.ROUND_HALF_UP);
                            map.put("val5", average.setScale(1,BigDecimal.ROUND_HALF_UP));
                        }
                    }
                    waiguan = waiguan && "合格".equals(ObjectUtils.isEmpty(detailDO.getCheckResult()) ? "" : detailDO.getCheckResult());
                    map.put("specification4", detailDO.getSpecification());
                    map.put("yangpin8", detailDO.getSample());
//                    map.put("result8", detailDO.getCheckResult());
                    break;
                case Constant.ZHURUKOUH://a>=58.4 && a<=59.6 && b>=58.4 && b<=59.6 && average>=58.4 && average<=59.6
                    if (!ObjectUtils.isEmpty(detailDO.getCheckValue())){
                        JSONArray array = JSON.parseArray(detailDO.getCheckValue());
                        if (!ObjectUtils.isEmpty(array)){
                            BigDecimal average = array.stream().collect(CustomCollectors.averagingBigDecimal(i -> new BigDecimal(i.toString()), 2, 2));
                            map.put("val4", average.setScale(1,BigDecimal.ROUND_HALF_UP));
                        }
                    }
//                    map.put("specification4", detailDO.getSpecification());
//                    map.put("yangpin8", detailDO.getSample());
                    waiguan = waiguan && "合格".equals(ObjectUtils.isEmpty(detailDO.getCheckResult()) ? "" : detailDO.getCheckResult());
//                    map.put("result8", detailDO.getCheckResult());
                    break;
                case Constant.HOUDU://min >= 3.5
                    map.put("specification5", detailDO.getSpecification());
                    map.put("yangpin9", detailDO.getSample());
                    map.put("result9", type.equals(2) ? (ok.equals(detailDO.getCheckResult()) ? "OK" : "NO") : detailDO.getCheckResult());
                    if (!ObjectUtils.isEmpty(detailDO.getCheckValue())){
                        JSONArray array1 = JSON.parseArray(detailDO.getCheckValue());
                        List<Object> array = array1.stream().map(val -> new BigDecimal(val.toString())).sorted().collect(Collectors.toList());
                        if (!ObjectUtils.isEmpty(array)){
                            map.put("val6", new BigDecimal(array.get(0).toString()).setScale(1,BigDecimal.ROUND_HALF_UP));
                            map.put("val7", new BigDecimal(array.get(1).toString()).setScale(1,BigDecimal.ROUND_HALF_UP));
                        }
                    }
                    break;
                case Constant.GAODU:// average <= 985 && average>=975
                    map.put("yangpin10", detailDO.getSample());
                    map.put("specification6", detailDO.getSpecification());
                    map.put("result10", type.equals(2) ? (ok.equals(detailDO.getCheckResult()) ? "OK" : "NO") : detailDO.getCheckResult());
                    if (!ObjectUtils.isEmpty(detailDO.getCheckValue())){
                        JSONArray array = JSON.parseArray(detailDO.getCheckValue());
                        if (!ObjectUtils.isEmpty(array)){
                            map.put("val8", new BigDecimal(array.get(1).toString()).setScale(1,BigDecimal.ROUND_HALF_UP));
                            map.put("val9", new BigDecimal(array.get(1).toString()).setScale(1,BigDecimal.ROUND_HALF_UP));
                        }
                    }
                    break;
                case Constant.KUANDU://average <= 595 && average >= 585
                    map.put("specification7", detailDO.getSpecification());
                    map.put("yangpin11", detailDO.getSample());
                    map.put("result11", type.equals(2) ? (ok.equals(detailDO.getCheckResult()) ? "OK" : "NO") : detailDO.getCheckResult());
                    if (!ObjectUtils.isEmpty(detailDO.getCheckValue())){
                        JSONArray array = JSON.parseArray(detailDO.getCheckValue());
                        if (!ObjectUtils.isEmpty(array)){
                            map.put("val10", new BigDecimal(array.get(0).toString()).setScale(1,BigDecimal.ROUND_HALF_UP));
                            map.put("val11", new BigDecimal(array.get(1).toString()).setScale(1,BigDecimal.ROUND_HALF_UP));
                        }
                    }
                    break;
                case Constant.ZHONGLIANG:// average <= 13.5 && average >=12.5
                    map.put("yangpin12", detailDO.getSample());
                    map.put("specification8", detailDO.getSpecification());
                    map.put("result12", type.equals(2) ? (ok.equals(detailDO.getCheckResult()) ? "OK" : "NO") : detailDO.getCheckResult());
                    if (!ObjectUtils.isEmpty(detailDO.getCheckValue())){
                        JSONArray array = JSON.parseArray(detailDO.getCheckValue());
                        if (!ObjectUtils.isEmpty(array)){
                            map.put("val12", new BigDecimal(array.get(0).toString()).setScale(1,BigDecimal.ROUND_HALF_UP));
                            map.put("val13", new BigDecimal(array.get(1).toString()).setScale(1,BigDecimal.ROUND_HALF_UP));
                        }
                    }
                    break;
                case Constant.RONGJI:// average >= 200
                    StringBuffer specification9 = new StringBuffer(detailDO.getSpecification());
                    specification9 = specification9.insert(detailDO.getSpecification().indexOf("≤")-1,"L");
                    map.put("specification9",specification9.toString());
                    map.put("yangpin13", detailDO.getSample());
                    map.put("result13", type.equals(2) ? (ok.equals(detailDO.getCheckResult()) ? "OK" : "NO") : detailDO.getCheckResult());
                    if (!ObjectUtils.isEmpty(detailDO.getCheckValue())){
                        JSONArray array = JSON.parseArray(detailDO.getCheckValue());
                        if (!ObjectUtils.isEmpty(array)){
                            map.put("val14", new BigDecimal(array.get(0).toString()).setScale(1,BigDecimal.ROUND_HALF_UP));
                            map.put("val15", new BigDecimal(array.get(1).toString()).setScale(1,BigDecimal.ROUND_HALF_UP));
                        }
                    }
                    break;
                default:
                    break;
            }
        }
        map.put("result8", type.equals(2) ? (waiguan ? "OK" : "NO") : (waiguan ? "合格" : "不合格"));
    }

    /**
     *
     * @param detailDOS
     * @param map
     * @param type 1-excel; 2-pdf
     */
    public void handleData(List<CheckResultDetailDO> detailDOS, Map<String,Object> map, Integer type) {
        String ok = "1";
        for (CheckResultDetailDO detailDO : detailDOS) {
            map.put("remark", detailDO.getCheckResult());
            map.put("formula", detailDO.getFormula());
            map.put("specification", detailDO.getSpecification());
            map.put("name", detailDO.getCheckItem());
            map.put("typeName", detailDO.getCheckType() != null ? detailDO.getCheckType() : "");
            map.put("sample", detailDO.getSample());
            map.put("method", detailDO.getCheckWay());
            map.put("targetValue", detailDO.getTargetValue());
            map.put("checkResult", detailDO.getCheckResult());

            String typeName = detailDO.getCheckItem()==null ? "" : detailDO.getCheckItem();
            switch (typeName) {
                case Constant.WAIGUAN://
                    map.put("result1", ok.equals(detailDO.getCheckResult()) ? "OK" : "NG");
                    map.put("val1", detailDO.getStatusValue());
                    break;
                case Constant.YANSE://
                    map.put("val2", detailDO.getStatusValue());
                    map.put("result2", ok.equals(detailDO.getCheckResult()) ? "OK" : "NG");
                    break;
                case Constant.MI://
                    map.put("val3", detailDO.getStatusValue());
                    map.put("result3", ok.equals(detailDO.getCheckResult()) ? "OK" : "NG");
                    break;
                case Constant.MIDU://
                    map.put("val4", detailDO.getStatusValue());
                    map.put("result4", ok.equals(detailDO.getCheckResult()) ? "OK" : "NG");
                    break;
                default:
                    break;
            }
        }
    }





}
